<template>
  <div style="height: 20px"></div>
  <n-space justify="center">
    <n-gradient-text
      type="warning"
      :size="24"
    >
      {{ chooseLifeModelName }}
    </n-gradient-text>
  </n-space>
  <n-space
    vertical
    size="large"
  >
    <n-layout-header bordered>
      <n-space justify="space-between">
        <n-gradient-text
          type="info"
          :size="24"
        >
          生活模式列表
        </n-gradient-text>
        <n-button
          @click="addNewOne()"
          type="primary"
          dashed
          >添加</n-button
        >
      </n-space>
    </n-layout-header>
    <n-layout>
      <n-layout-content content-style="padding: 24px;">
        <n-data-table
          v-show="!showEmpty"
          :columns="columns"
          handle="#handle-drag"
          :data="tableData"
          :pagination="false"
          :bordered="false"
          id="modelDragTable"
          :row-props="rowProps"
        />
        <n-data-table
          v-show="showEmpty"
          :columns="columns"
          :data="[]"
          :pagination="false"
          :bordered="false"
        />
      </n-layout-content>
    </n-layout>
  </n-space>
  <n-dropdown
    placement="bottom-start"
    trigger="manual"
    :x="xRef"
    :y="yRef"
    :options="options"
    :show="showDropdownRef"
    :on-clickoutside="onClickoutside"
    @select="handleSelect"
  />
  <LifeModelEditDrawer v-model="editSettings"></LifeModelEditDrawer>
  <LifeModelDeletModal v-model="editSettings"></LifeModelDeletModal>
</template>
<script lang="ts">
import Sortable from "sortablejs";
</script>
<script lang="ts" setup>
import { h, reactive, ref, onMounted, computed } from "vue";
import { NDataTable, NButton, NSpace, NLayout, NLayoutContent, NLayoutHeader } from "naive-ui";
import pinia from "@pinias/pinia";
import UseLifeModel from "@pinias/UseLifeModel";
import LifeModelEditDrawer from "./lifeModelButton/LifeModelEditDrawer.vue";
import LifeModelDeletModal from "./lifeModelButton/LifeModelDeletModal.vue";
import { RemoveMethods } from "@/types/remove-methods";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import { SurfaceSetting } from "@model/surfaceSetting";

// 全局数据
const { getLifeModel } = UseLifeModel(pinia);
const lifeModel = getLifeModel();
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting: SurfaceSetting = getSurfaceSetting();
// 当前页面数据
const showEmpty = ref(false);
const chooseLifeModelName = computed(() => {
  const choose = lifeModel.chooseLifeModel;
  const chooseData = lifeModel.getLifeModelDataById(choose);
  if (chooseData === undefined) return "未选择生活模式";
  else return "正进行的生活模式:" + chooseData.name;
});
const editSettings = reactive<{ toEdit: boolean; toDelete: boolean; toDealRowId: number | undefined }>({
  toEdit: false,
  toDelete: false,
  toDealRowId: undefined,
});
class RowData {
  id: number;
  name: string;
  desc: string;
  constructor(data: RemoveMethods<RowData>) {
    Object.assign(this, data);
  }
  static getNullModel() {
    return new RowData({
      id: -1,
      name: "",
      desc: "",
    });
  }
}

// 表格数据
const getTableData = () => {
  const result = [];
  const list = lifeModel.list;
  const data = lifeModel.data;
  for (var i = 0; i < list.length; i++) {
    const id = list[i];
    const oldDdata = data.find((value, index, obj) => value.id === id);
    if (oldDdata !== undefined) {
      result.push(
        new RowData({
          id: oldDdata.id,
          name: oldDdata.name,
          desc: oldDdata.desc,
        }),
      );
    }
  }
  if (result.length == 0) {
    result.push(RowData.getNullModel());
    showEmpty.value = true;
  } else showEmpty.value = false;
  return result;
};
let tableData = ref(getTableData());
const createColumns = () => {
  return [
    {
      title: "名字",
      key: "name",
      resizable: true,
    },
    {
      title: "描述",
      key: "desc",
      resizable: true,
    },
    {
      title: "Action",
      key: "actions",
      render(row: RowData) {
        return [
          h(
            NButton,
            {
              strong: true,
              tertiary: true,
              size: "small",
              id: "handle-drag",
              onClick: () => show(row),
            },
            { default: () => "上下移动" },
          ),
        ];
      },
    },
  ];
};
const columns = createColumns();
const show = (row: RowData) => {
  console.log(row);
};
// 右键菜单
const rowProps = (row: RowData) => {
  return {
    onContextmenu: (e: MouseEvent) => {
      // message.info(JSON.stringify(row, null, 2));
      showDropdownRef.value = true;
      xRef.value = e.clientX;
      yRef.value = e.clientY;
      // console.log('rowProps',row)
      editSettings.toDealRowId = row.id;
    },
  };
};
const options = [
  {
    label: "选择生活",
    key: "live",
  },
  {
    label: "查看",
    key: "show",
  },
  {
    label: "编辑",
    key: "edit",
  },
  {
    label: () => h("span", { style: { color: "red" } }, "删除"),
    key: "delete",
  },
];
const showDropdownRef = ref(false);
const xRef = ref(0);
const yRef = ref(0);
const onClickoutside = () => {
  showDropdownRef.value = false;
};
const handleSelect = (key: string, node: string) => {
  // console.log(key, node);
  showDropdownRef.value = false;
  if (key == "edit") {
    editSettings.toEdit = true;
  }
  if (key == "delete") {
    editSettings.toDelete = true;
  }
  if (key == "show") {
    if (editSettings.toDealRowId !== undefined) surfaceSetting.showLifeModel = editSettings.toDealRowId;
  }
  if (key == "live") {
    if (editSettings.toDealRowId !== undefined) lifeModel.chooseLifeModel = editSettings.toDealRowId;
  }
};
const addNewOne = () => {
  editSettings.toDealRowId = undefined;
  editSettings.toEdit = true;
};

// 拖拽逻辑
function setSort() {
  const el = document.querySelector("#modelDragTable table tbody");
  // console.log('el',el);
  new Sortable(el, {
    handle: "#handle-drag",
    sort: true,
    ghostClass: "sortable-ghost",
    onEnd: function (/**Event*/ e: any) {
      const targetRow = lifeModel.list.splice(e.oldIndex, 1)[0];
      lifeModel.list.splice(e.newIndex, 0, targetRow);
    },
  });
}
onMounted(() => {
  setSort();
});
</script>
